﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Browser;
using Galaktika.BI.Runtime.Services;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.DataAccess;
using Galaktika.BI.Silverlight.Services;
using Ranet.Olap.Core.Data;
using Ranet.AgOlap.Controls.DataSourceInfo;
using Ranet.Olap.Core.Providers.ClientServer;

namespace Galaktika.BI.Silverlight.ClientApp.Web.Commands.PivotGrid
{
    public class ServiceCommand : Galaktika.BI.Silverlight.Commands.ServerCommand
    {
        public ServiceCommand(InvokeSchema invoker)
            : base(Galaktika.BI.Silverlight.Commands.CommandId.ServiceCommandId)
        {
            this.Schema = invoker;
            this.ContextId = invoker[KnownInvokeArgs.ContextId];
            this.DataSourceId = invoker[KnownInvokeArgs.DataSourceId];
            this.Args = invoker[KnownInvokeArgs.PivotGridServiceCommand];
        }

        public InvokeSchema Schema { get; private set; }
        public string ContextId { get; private set; }
        public string DataSourceId { get; private set; }
        public string Args { get; private set; }

        private IBindingContext Context
        {
            get
            {
                return DataBinder.Current.GetContext(this.ContextId);
            }
        }

        private OlapDataManager DataManager
        {
            get
            {
                IBindingManager bindingMgr = DataBinder.Current.GetBindingManager(this.ContextId, this.DataSourceId);
                if (bindingMgr != null)
                {
                    return bindingMgr.DataManager as OlapDataManager;
                }

                return null;
            }
        }

        public override InvokeResultSchema Invoke()
        {
            InvokeResultSchema res = new InvokeResultSchema(base.Id);
            res.ContentType = KnownContentTypes.MultidimData;

            ServiceCommandArgs args = XmlUtility.XmlStr2Obj<ServiceCommandArgs>(this.Args);
            if (DataManager != null && args != null)
            {
                // Заглушка - т.к. несколько раз была ситуация когда DataManager.Context оставался null
                if (DataManager.Context == null)
                    DataManager.Context = this.Context;

                switch (args.Command)
                {
                    case ServiceCommandType.Forward:
                        DataManager.History.MoveNext();
                        break;
                    case ServiceCommandType.Back:
                        DataManager.History.MoveBack();
                        break;
                    case ServiceCommandType.ToBegin:
                        DataManager.History.ToBegin();
                        break;
                    case ServiceCommandType.ToEnd:
                        DataManager.History.ToEnd();
                        break;
                    case ServiceCommandType.HideEmptyColumns:
                        DataManager.HideEmptyColumns = true;
                        break;
                    case ServiceCommandType.ShowEmptyColumns:
                        DataManager.HideEmptyColumns = false;
                        break;
                    case ServiceCommandType.RotateAxes:
                        DataManager.RotateAxes = true;
                        break;
                    case ServiceCommandType.NormalAxes:
                        DataManager.RotateAxes = false;
                        break;
                    case ServiceCommandType.HideEmptyRows:
                        DataManager.HideEmptyRows = true;
                        break;
                    case ServiceCommandType.ShowEmptyRows:
                        DataManager.HideEmptyRows = false;
                        break;
                    case ServiceCommandType.GetDataSourceInfo:
                        DataSourceInfoArgs info = DataManager.GetDataSourceInfo(args);
                        res.Content = XmlUtility.Obj2XmlStr(info, Common.Namespace);
                        return res;
                    case ServiceCommandType.ExportToExcel:
                        //using (var srv = new SyncDataService())
                        //{
                        //    String query = DataManager.WrappedQuery;
                        //    // Парсинг запросов
                        //    IExecutionContext exe = (IExecutionContext)Context.Services.GetService(typeof(IExecutionContext));
                        //    if (exe != null)
                        //    {
                        //        query = exe.Parse(Context, query);
                        //    }

                        //    this.Schema.Args.Add(new InvokeArg(KnownInvokeArgs.Query, query));
                        //    this.Schema.Args.Add(new InvokeArg(KnownInvokeArgs.ConnectionString, DataManager.ConnectionString));
                        //    InvokeResultSchema result = srv.InvokeCommand(this.Schema);
                        //    if (result != null)
                        //    {
                        //        res.Content = result.Content;
                        //    }
                        //}
                        //return res;

                        IUserTaskManager taskMgr = (IUserTaskManager)this.Context.Services.GetService(typeof(IUserTaskManager));
                        if (taskMgr != null)
                        {
                            String query = DataManager.WrappedQuery;
                            String connectionString = DataManager.ConnectionString;
                            // Парсинг запросов
                            IExecutionContext exe = (IExecutionContext)Context.Services.GetService(typeof(IExecutionContext));
                            if (exe != null)
                            {
                                query = exe.Parse(Context, query);
                            }


                            using (SyncPivotGridService pivotGridService = new SyncPivotGridService())
                            {
                                pivotGridService.ExportToExcel(connectionString, query);
                                string address = String.Format(
                                           "{0}PivotGridExportHandler.asmx?token={1}",
                                           Galaktika.BI.Runtime.Services.ServiceManagerHelper.GetBaseUri(),
                                           pivotGridService.Token);
                                taskMgr.Dispatcher.BeginInvoke(() =>
                                {
                                    HtmlPage.Window.Invoke("open", address);
                                });
                            }
                        }
                        return res;
                }
                CellSetData csd = DataManager.RefreshQuery();
                res.Content = CellSetData.Serialize(csd);
                //res.Content = XmlUtility.Obj2XmlStr(csd, Common.Namespace);
            }

            return res;
        }
    }
}
